﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
using System.Data;
using JYB.SummitExam.Model;
using System.Configuration;
namespace JYB.SummitExam.DAL {
	public class Common {
	
		#region 获取单个实例
		//获取单个实例
		public static T GetEntity<T>(string name, string pwd) where T : BaseModel {
			string SqlText = "select {0} from [{1}] where Student_Name=@Name and Student_Pwd= @Pwd ";
			Type type = typeof(T);
			var SelectField = string.Join(",", type.GetProperties().Select(p => string.Format("[{0}]", p.Name)));
			/// string.Join(); 第一个参数是连接符   第二个参数是个集合
			/// 表示 用"," 将后面集合中的每个元素拼接成字符串
			SqlText = string.Format(SqlText, SelectField, type.Name, name, pwd);
			var oObject = (T)Activator.CreateInstance(type);
			using (SqlConnection con = new SqlConnection(sqlstr)) {
				con.Open();
				SqlCommand com = new SqlCommand(SqlText, con);
				//SqlParameter spid = new SqlParameter();
				//spid.Value = "@id";
				//com.Parameters.Add(spid);
				com.Parameters.Add(new SqlParameter("@Name", name));
				com.Parameters.Add(new SqlParameter("@Pwd", pwd));
				SqlDataReader reader = com.ExecuteReader();
				while (reader.Read()) {
					foreach (var pop in type.GetProperties()) {
						object oValue = reader[pop.Name];
						if (oValue is DBNull) {
							pop.SetValue(oObject, null);
						}
						else {
							pop.SetValue(oObject, oValue);
						}
					}
				}
			}
			return oObject;
		}
		#endregion
		#region 获取列表
		public List<T> GetList<T>() where T : BaseModel {
			string sql = "select {0} from [{1}]";
			Type type = typeof(T);
			var SelectField = string.Join(",", type.GetProperties().Select(p => string.Format("{0}", p.Name)));
			sql = string.Format(sql, SelectField, type.Name);
			List<T> list = new List<T>();
			using (SqlConnection con = new SqlConnection(sqlstr)) {
				con.Open();
				SqlCommand com = new SqlCommand(sql, con);
				SqlDataReader reader = com.ExecuteReader();
				while (reader.Read()) {
					var oObject = (T)Activator.CreateInstance(type);
					foreach (var item in type.GetProperties()) {
						object oValue = reader[item.Name];
						if (oValue is DBNull) {
							item.SetValue(oObject, null);
						}
						else {
							item.SetValue(oObject, oValue);
						}
					}
				}
			}
			return list;
		}

		#endregion
	}
}
